<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12">
        <h2>用户发布统计</h2>
      </el-col>
      <el-col :span="12">
      <el-select v-model="selectedMode" placeholder="Select mode" @change="updateChart" style="width: 200px;">
          <el-option label="Daily" value="daily" />
          <el-option label="Monthly" value="monthly" />
    </el-select>
      </el-col>
    </el-row>

    <v-chart class="chart" :option="option" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getUserPostStatistics } from '@/api/wallpaper/posting.js';
import { ElSelect, ElOption } from 'element-plus';

// 定义响应式数据
const data = ref([]);
const selectedMode = ref('daily'); // 默认统计模式为日

// 处理数据，按选择的模式分组统计
const processData = (rawData, mode) => {
  const dateCounts = rawData.reduce((acc, { date, count }) => {
    let key;
    if (mode === 'daily') {
      key = date.split(' ')[0]; // 提取日期部分，格式为 'YYYY-MM-DD'
    } else if (mode === 'monthly') {
      key = date.split(' ')[0].split('-').slice(0, 2).join('-'); // 提取月份部分，格式为 'YYYY-MM'
    }
    if (!acc[key]) {
      acc[key] = 0;
    }
    acc[key] += count;
    return acc;
  }, {});

  // 转换为数组格式，以便 ECharts 使用
  return Object.keys(dateCounts).map(key => ({
    date: key,
    count: dateCounts[key]
  }));
};

// 计算属性生成 ECharts 配置项
const option = computed(() => {
  const processedData = processData(data.value, selectedMode.value);
  return {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: processedData.map(v => v.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '发布数量',
        type: 'line',
        data: processedData.map(v => v.count)
      }
    ]
  };
});

// 定义一个函数来获取数据
const fetchData = async () => {
  try {
    const response = await getUserPostStatistics();
    if (response.code === 200) {
      data.value = response.data;
      console.log('Fetched data:', data.value);
    } else {
      console.error('Failed to fetch data:', response.msg);
    }
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
};

// 更新图表
const updateChart = () => {
  // 当选择器改变时，重新计算 ECharts 配置项
  option.value;
};

// 在组件挂载时获取数据
onMounted(fetchData);

</script>

<style scoped>
.chart {
  height: 400px;
}
</style>
